package com.uiotsoft.small.app.sampler.mqtt;

import com.uiotsoft.small.app.entity.AppClient;
import com.uiotsoft.small.app.service.connect.AppLogin;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AppLocalLoginSampler extends AbstractJavaSamplerClient {
    private volatile AppClient appClient;
    private static final Logger log = LoggerFactory.getLogger(AppLocalLoginSampler.class);

    public Arguments getDefaultParameters() {
        Arguments params = new Arguments();
        params.addArgument("env", "chk.local");
        params.addArgument("mobile", "15286800731");
        params.addArgument("si", "57049b2f1b1ed62s");
        params.addArgument("sn", "2211d011d7db485187e41dad565ad378");
        params.addArgument("mqttUrl", "tcp://:1883");
        params.addArgument("userUnique", "9bfec69bf8ae179ece5cf6775468ee6a");
        return params;
    }

    private void setupValues(JavaSamplerContext context) {
        String env = context.getParameter("env");
        String mobile = context.getParameter("mobile");
        String si = context.getParameter("si");
        String sn = context.getParameter("sn");
        //本地登录需要设置
        String mqttUrl = context.getParameter("mqttUrl");
        String userUnique = context.getParameter("userUnique");
        appClient = new AppClient(env,mobile,si,sn);
        appClient.setMqttUrl(mqttUrl);
        appClient.setUserUnique(userUnique);
    }

    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        setupValues(javaSamplerContext);
        JMeterVariables vars = JMeterContextService.getContext().getVariables();
        SampleResult results = new SampleResult();
        results.setDataEncoding("UTF-8");
        results.sampleStart();
        try {
            if (appClient.connect()){
                AppLogin appLogin = new AppLogin(appClient);
                if (appLogin.loginToLocal()){
                    log.debug("app 本地登录成功***{}",appClient);
                    vars.putObject("appClient", appClient);
                    results.sampleEnd();
                    results.setSuccessful(true);
                    results.setResponseData("OK", "UTF-8");
                    return results;
                }
            }else {
                results.setSuccessful(false);
                results.setResponseData("connect fail !", "UTF-8");
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
        results.sampleEnd();
        return results;
    }
}
